package com.dailyblue.java.project.oa.commons.filter;


import com.dailyblue.java.project.oa.commons.bean.Power;
import com.dailyblue.java.project.oa.commons.config.JwtConfig;
import com.dailyblue.java.project.oa.commons.mapper.PowerMapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CheckIsLoginFilter extends BasicAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    private StringRedisTemplate stringRedisTemplate;
    private PowerMapper powersMapper;

    public CheckIsLoginFilter(AuthenticationManager authenticationManager, StringRedisTemplate stringRedisTemplate, PowerMapper powersMapper) {
        super(authenticationManager);
        this.authenticationManager = authenticationManager;
        this.stringRedisTemplate = stringRedisTemplate;
        this.powersMapper = powersMapper;
    }

    /*
    验证用户是否登陆
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if(token!=null){
            boolean b = JwtConfig.checkToken(token);
            if(b){
                String id = JwtConfig.getMemberIdByJwtToken(request);
                String redisToken = stringRedisTemplate.opsForValue().get("token:"+id);
                if(token.equals(redisToken)){
                    List<Power> list = powersMapper.findPowerByUserId(Integer.parseInt(id));
                    List<GrantedAuthority> authorities = new ArrayList<>();
                    for(Power power:list){
                        GrantedAuthority g = new SimpleGrantedAuthority(power.getPowerName());
                        authorities.add(g);
                    }
                    UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(id,token,authorities);
                    SecurityContextHolder.getContext().setAuthentication(upat);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
